package com.itlong.cloud.controller.nonstandard;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.property.PropertyGetElevatorNameAndDeviceUniqueVO;
import com.itlong.cloud.enumerate.CloudEntranceOpenTypeEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.commons.ICloudEntranceServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      华为烟感报警回调
 * </desc>
 *
 * @createDate 2020/04/07
 */
@RestController
@RequestMapping("/nonstandard/hw")
//@RequestMapping("/nonstandard/hw/iot/callback")
public class SmokeAlarmController {
    private static final Logger LOG = LoggerFactory.getLogger(SmokeAlarmController.class);

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    ICloudEntranceServiceClient iCloudEntranceServiceClient;

//    /**
//     * <desc>
//     *      华为触发烟感报警
//     * </desc>
//     *
//     * @param httpServletRequest
//     * @return
//     * @author Jiaqi.X
//     * @createDate 2020/04/07
//     */
//    @RequestMapping("alarm")
//    @ResponseBody
//    public MessageVO smokeAlarm(HttpServletRequest httpServletRequest) throws Exception {
//        String jsonStr = getRequestPostStr(httpServletRequest);
//        if (StringUtils.isBlank(jsonStr)) {
//            return null;
//        }
//        LOG.info("华为推送烟感数据:"+jsonStr);
//        Map<String,Object> params = JsonUtil.toObject(jsonStr, HashMap.class);
//        if(params.get("resource") !=null && params.get("resource").toString().equals("device.data")) {
//            Map<String, Object> notifyData = (HashMap) params.get("notify_data");
//            List<Map<String, Object>> services = (ArrayList) notifyData.get("services");
//            for(Map<String,Object> mp : services){
//                if ((mp.get("service_id") == null ||  mp.get("data") == null) || (mp.get("service_id") != null && !mp.get("service_id").toString().equals("alarm")) ) {//设备上报状态
//                    continue;
//                }
//                Map<String,Object> data = (HashMap)mp.get("data");
//                String alarm = data.get("alarm").toString();
//                //查询电梯设备
//                List<PropertyGetElevatorNameAndDeviceUniqueVO> elevators = iPropertyEquipServiceClient.getElevatorByProjectId("10060001");
////                List<PropertyGetElevatorNameAndDeviceUniqueVO> elevators = iPropertyEquipServiceClient.getElevatorByProjectId("00000144");
//                //查询门禁信息
//                List<Map<String,Object>> entrances = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKeyByProjectId("10060001");
////                List<Map<String,Object>> entrances = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKeyByProjectId("00000144");
//                if(alarm.equals("1") || alarm.equals("13")){
//                    //控制设备报警
//                    for(PropertyGetElevatorNameAndDeviceUniqueVO vo : elevators){
//                        iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(vo.getDeviceUnique(),"1");
//                    }
//                    for(Map<String,Object> entrance : entrances){
//                        String deviceUnique = entrance.get("deviceUnique").toString();
//                        iCloudEntranceServiceClient.entranceOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
//                                entrance.get("deviceId").toString(),
//                                CloudEntranceOpenTypeEnum.OPEN.getType().toString(), "0", entrance.get("productKey").toString(), "119fireAlarm", LogicIdUtil.bussinessId(),"0");
//                    }
//                }else{
//                    //解除设备报警
//                    for(PropertyGetElevatorNameAndDeviceUniqueVO vo : elevators){
//                        iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(vo.getDeviceUnique(),"0");
//                    }
//                    for(Map<String,Object> entrance : entrances){
//                        iCloudEntranceServiceClient.entranceOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
//                                entrance.get("deviceId").toString(),
//                                CloudEntranceOpenTypeEnum.CLOSE.getType().toString(), "0", entrance.get("productKey").toString(), "119fireAlarm", LogicIdUtil.bussinessId(),"0");
//                    }
//                }
//            }
//        }
//        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
//    }



    /**
     * <desc>
     *      华为触发烟感报警测试接口
     * </desc>
     *
     * @return
     * @author Jiaqi.X
     * @createDate 2020/04/07
     */
    @RequestMapping("alarm")
    @ResponseBody
    public Object testAlarm(String alarm,HttpServletRequest request) throws Exception {
        alarm = StringHandlerUtil.getNullOrStringForObject(request.getAttribute("alarm"));
        //查询电梯设备
        List<PropertyGetElevatorNameAndDeviceUniqueVO> elevators = iPropertyEquipServiceClient.getElevatorByProjectId("10060001",null,null);
        //查询门禁信息
        List<Map<String,Object>> entrances = iCloudEntranceServiceClient.getMainDeviceUniqueAndProductKeyByProjectId("10060001");
        if(alarm.equals("1")){
            //控制设备报警
            for(PropertyGetElevatorNameAndDeviceUniqueVO vo : elevators){
                iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(vo.getDeviceUnique(),"1");
            }
            for(Map<String,Object> entrance : entrances){
                iCloudEntranceServiceClient.entranceOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                        entrance.get("deviceId").toString(),
                        CloudEntranceOpenTypeEnum.OPEN.getType().toString(), "0", entrance.get("productKey").toString(), "119fireAlarm", LogicIdUtil.bussinessId(),"0");
            }
        }else{
            //解除设备报警
            for(PropertyGetElevatorNameAndDeviceUniqueVO vo : elevators){
                iAppDeviceServiceClient.setCloudElevatorSpecialUseModel(vo.getDeviceUnique(),"0");
            }
            for(Map<String,Object> entrance : entrances){
                iCloudEntranceServiceClient.entranceOpenOrCloseCtrl("itlong", entrance.get("deviceUnique").toString(),
                        entrance.get("deviceId").toString(),
                        CloudEntranceOpenTypeEnum.CLOSE.getType().toString(), "0", entrance.get("productKey").toString(), "119fireAlarm", LogicIdUtil.bussinessId(),"0");
            }
        }
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
    }

    /**
     * 描述:获取 post 请求内容
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public  String getRequestPostStr(HttpServletRequest request)
            throws IOException {
        byte buffer[] = getRequestPostBytes(request);
        String charEncoding = request.getCharacterEncoding();
        if (charEncoding == null) {
            charEncoding = "UTF-8";
        }
        return new String(buffer, charEncoding);
    }

    /**
     * 描述:获取 post 请求的 byte[] 数组
     * <pre>
     * 举例：
     * </pre>
     * @param request
     * @return
     * @throws IOException
     */
    public static byte[] getRequestPostBytes(HttpServletRequest request)
            throws IOException {
        int contentLength = request.getContentLength();
        if(contentLength<0){
            return null;
        }
        byte buffer[] = new byte[contentLength];
        for (int i = 0; i < contentLength;) {

            int readlen = request.getInputStream().read(buffer, i,
                    contentLength - i);
            if (readlen == -1) {
                break;
            }
            i += readlen;
        }
        return buffer;
    }
}